package vip.specimen.system.common.implement;

import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.exception.CosClientException;
import com.qcloud.cos.exception.CosServiceException;
import com.qcloud.cos.http.HttpProtocol;
import com.qcloud.cos.model.*;
import com.qcloud.cos.region.Region;
import com.qiniu.http.Response;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.conn.HttpHostConnectException;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import vip.specimen.system.common.connector.SaveMethodInterface;
import vip.specimen.system.common.enums.ResultCode;
import vip.specimen.system.common.enums.SaveMethodEnum;
import vip.specimen.system.common.handler.SystemExceptionHandler;
import vip.specimen.system.datasource.entity.SystemResourceEntity;
import vip.specimen.system.datasource.entity.SystemResourceSuffixEntity;
import vip.specimen.system.datasource.entity.SystemSaveConfigEntity;
import vip.specimen.system.result.JsonResult;
import vip.specimen.system.service.SystemResourceService;
import vip.specimen.system.service.SystemResourceSuffixService;
import vip.specimen.system.service.SystemSaveConfigService;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

/**
 * *@Author: 余浪人
 * *@Date：2021/04/18 10:51
 * *@Email:yulangren520@Gmail.com
 * *@QQ:1368419640
 **/
@Getter
@Setter
@Slf4j
@Component
public class TencentUpload implements SaveMethodInterface {
    private String bucketName = "examplebucket-125x";
    private String secretId = "COS_SECRETID";
    private String secretKey = "COS_SECRETKEY";
    private String domain;
    private COSClient cosClient;
    @Resource
    private SystemSaveConfigService saveConfigService;
    @Resource
    private SystemResourceService resourceService;
    @Resource
    private SystemResourceSuffixService resourceSuffixService;
    public static TencentUpload tencentUpload;

    @Override
    @PostConstruct
    public void init() {
        tencentUpload = this;
        tencentUpload.resourceSuffixService = resourceSuffixService;
        tencentUpload.resourceService = resourceService;
        tencentUpload.saveConfigService = saveConfigService;
        SystemSaveConfigEntity configEntity = tencentUpload.saveConfigService.getConfig();
        tencentUpload.bucketName = configEntity.getTencentBucketName();
        tencentUpload.secretId = configEntity.getTencentSecretId();
        tencentUpload.secretKey = configEntity.getTencentSecretKey();
        tencentUpload.domain = configEntity.getTencentDomain();
        Region region = new Region(configEntity.getTencentRegion());
        ClientConfig clientConfig = new ClientConfig(region);
        clientConfig.setHttpProtocol(HttpProtocol.https);
        cosClient = new COSClient(new BasicCOSCredentials(tencentUpload.secretId, tencentUpload.secretKey), clientConfig);
    }

    @Override
    public JsonResult<SystemResourceEntity> upload(MultipartFile file) {
        String originalName = file.getOriginalFilename();
        String uuid = UUID.randomUUID().toString().substring(0, 8);
        String suffix = originalName.substring(originalName.indexOf(".")).toLowerCase();
        SystemResourceSuffixEntity suffixEntity = tencentUpload.resourceSuffixService.findBySuffix(suffix);
        if (null == suffixEntity || !suffixEntity.isEnable() || null == suffixEntity.getKindEntity() || !suffixEntity.getKindEntity().isEnable()) {
            throw new SystemExceptionHandler(ResultCode.ERROR_UPLOAD_NOT_ALLOW);
        }
        String path = suffixEntity.getKindEntity().getPath().startsWith("/") ? suffixEntity.getKindEntity().getPath().substring(1) : suffixEntity.getKindEntity().getPath();
        String name = uuid + suffix;
        String fileName = !path.endsWith("/") ? path + "/" + name : path + name;
        ObjectMetadata objectMetadata = new ObjectMetadata();
        objectMetadata.setContentType(file.getContentType());
        objectMetadata.setContentLength(file.getSize());
        try {
            PutObjectRequest putObjectRequest = new PutObjectRequest(tencentUpload.bucketName, fileName, file.getInputStream(), objectMetadata);
            putObjectRequest.setStorageClass(StorageClass.Standard);
            putObjectRequest.setTrafficLimit(80 * 1024 * 1024);
            tencentUpload.cosClient.putObject(putObjectRequest);
        } catch (IOException e) {
            log.error("腾讯云上传异常:" + e.getMessage());
            e.printStackTrace();
            throw new SystemExceptionHandler(ResultCode.ERROR_UPLOAD_FAILED);
        }
        String resourceUrl = tencentUpload.domain + "/" + fileName;
        SystemResourceEntity resource = tencentUpload.resourceService.insert(new SystemResourceEntity(name, file.getSize(), originalName, resourceUrl, file.getContentType(), suffixEntity, SaveMethodEnum.Tencent, fileName));
        return JsonResult.success(resource);
    }

    @Override
    public void download(String fileName) {
        GetObjectRequest getObjectRequest = new GetObjectRequest(tencentUpload.bucketName, fileName);
        getObjectRequest.setTrafficLimit(80 * 1024 * 1024);
        COSObject cosObject = tencentUpload.cosClient.getObject(getObjectRequest);
        COSObjectInputStream cosObjectInput = cosObject.getObjectContent();
        try {
            cosObjectInput.close();// 关闭输入流
        } catch (IOException e) {
            log.error("腾讯云下载异常:" + e.getMessage());
            e.printStackTrace();
        }
    }

    @Override
    public boolean delete(String key) {
        try {
            tencentUpload.cosClient.deleteObject(tencentUpload.bucketName, key);
        } catch (Exception e) {
            log.error("腾讯云删除:[" + key + "]异常");
            return false;
        }
        return true;
    }

    @Override
    public List getFileList() {
        return null;
    }
}
